package com.zhht.htzx.ui;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static com.nsgf.library.photopicker.PhotoPicker.EXTRA_VIEW_ID;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.kunminx.binding_state.BR;
import com.nsgf.library.data.api.AccountService;
import com.nsgf.library.data.bean.BusinessBean;
import com.nsgf.library.data.bean.BusinessSettleTypeBean;
import com.nsgf.library.data.bean.ConfirmOrderBean;
import com.nsgf.library.data.bean.LibraryInfo;
import com.nsgf.library.data.bean.WorkOrderDetailBean;
import com.nsgf.library.data.repository.DataRepository;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.domain.request.BaseHttpObserver;
import com.nsgf.library.domain.request.HttpOnNextListener;
import com.nsgf.library.matisse.Matisse;
import com.nsgf.library.matisse.MimeType;
import com.nsgf.library.photopicker.PhotoPicker;
import com.nsgf.library.photopicker.widget.MultiPickResultView;
import com.nsgf.library.photopicker.widget.PhotoAdapter;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.ui.page.WebViewActivity;
import com.nsgf.library.ui.page.WebViewApiActivity;
import com.nsgf.library.ui.product.ConfirmOrderActivity;
import com.nsgf.library.utils.ToastUtils;
import com.nsgf.library.widget.prckerview.OptionsPickerView;
import com.zhht.htzx.R;
import com.zhht.htzx.databinding.ActivityBusinessSettleBinding;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 商家入驻
 */
public class BusinessSettledActivity extends BaseActivity {

    private BusinessSettleStateHolder mStates;
    private AccountRequester mAccountRequester;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(BusinessSettleStateHolder.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_business_settle, BR.vm, mStates)
                .addBindingParam(BR.click, new ClickProxy());
    }

    private ActivityBusinessSettleBinding mBinding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mStates.titleBar.set("商家入驻");
        getLifecycle().addObserver(mAccountRequester);
        mBinding = (ActivityBusinessSettleBinding) getBinding();
        mAccountRequester.getShopTypes();
        mAccountRequester.getLibraryList().observe(this, new Observer<ResponseStatus<List<LibraryInfo>>>() {
            @Override
            public void onChanged(ResponseStatus<List<LibraryInfo>> listResponseStatus) {
                if (listResponseStatus.getResponseCode() == 0) {
                    mStates.shopTypes.set(listResponseStatus.getData());
                }
            }
        });
        mAccountRequester.queryServiceCenters();
        mAccountRequester.getBusinessResult().observe(this, new Observer<ResponseStatus<List<BusinessBean>>>() {
            @Override
            public void onChanged(ResponseStatus<List<BusinessBean>> listResponseStatus) {
                if (listResponseStatus.getResponseCode() == 0) {
                    mStates.serviceTypes.set(listResponseStatus.getData());
                }
            }
        });

        mBinding.mprvPermit.init(this,
                MultiPickResultView.ACTION_SELECT,
                new ArrayList<>(),
                1,
                2,
                MimeType.ofAll(), new PhotoAdapter.PhotoOnClick() {
                    @Override
                    public void setPhotoListener(int position) {
                        mBinding.mprvPermit.photoAdapter.getPhotoPaths().remove(position);
                    }
                });

        mBinding.mprvCertificate.init(this,
                MultiPickResultView.ACTION_SELECT,
                new ArrayList<>(),
                2,
                0,
                MimeType.ofAll(), new PhotoAdapter.PhotoOnClick() {
                    @Override
                    public void setPhotoListener(int position) {
                        mBinding.mprvCertificate.photoAdapter.getPhotoPaths().remove(position);
                    }
                });

        mBinding.mprvCompany.init(this,
                MultiPickResultView.ACTION_SELECT,
                new ArrayList<>(),
                4,
                1,
                MimeType.ofAll(), new PhotoAdapter.PhotoOnClick() {
                    @Override
                    public void setPhotoListener(int position) {
                    }
                });


        mAccountRequester.getSrcSuccess().observe(this, new Observer<ResponseStatus<String>>() {
            @Override
            public void onChanged(ResponseStatus<String> stringResponseStatus) {
                getController().dismissLoading();
                if (stringResponseStatus.getResponseCode() == 0) {
                    ToastUtils.showShortToast(stringResponseStatus.getMsg());
                    finish();
                }
            }
        });
        mAccountRequester.getTenantTypes();
        mAccountRequester.getBusinessSettleTypeResult().observe(this, new Observer<ResponseStatus<List<BusinessSettleTypeBean>>>() {
            @Override
            public void onChanged(ResponseStatus<List<BusinessSettleTypeBean>> listResponseStatus) {
                if (listResponseStatus.getResponseCode() == 0) {
                    mBinding.radioTagGroup.setTags(listResponseStatus.getData());
                    // 设置选择监听器
                    mBinding.radioTagGroup.setOnTagSelectedListener((position, tag) -> {
                        if (position == 1) {
                            mBinding.llBusinessType.setVisibility(VISIBLE);
                        } else {
                            mBinding.llBusinessType.setVisibility(GONE);
                        }
                        mStates.zhhtMerchantsType.set(listResponseStatus.getData().get(position).getTypeId());
                    });
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (RESULT_OK == resultCode) {
            if (PhotoPicker.REQUEST_CODE == requestCode) {
                getController().displayLoading();
                int index = data.getIntExtra(EXTRA_VIEW_ID, 0);

                ArrayList<WorkOrderDetailBean.FileDto> photos = new ArrayList<>();
                for (String src : Matisse.obtainPathResult(data)) {
                    WorkOrderDetailBean.FileDto dto = new WorkOrderDetailBean.FileDto();
                    dto.setFilePath(src);
                    photos.add(dto);
                }

                switch (index) {
                    case 0:
                        mBinding.mprvCertificate.photoAdapter.refresh(photos);
                        break;
                    case 1:
                        mBinding.mprvCompany.photoAdapter.refresh(photos);

                        break;
                    case 2:
                        mBinding.mprvPermit.photoAdapter.refresh(photos);

                        break;
                }
                List<String> arrayList = new ArrayList<>();

                for (WorkOrderDetailBean.FileDto fileDto : photos) {
//                    mAccountRequester.uploadFile(fileDto.getFilePath());

                    File file = new File(fileDto.getFilePath());
                    RequestBody requestBody = RequestBody.create(file, MediaType.parse("multipart/form-data"));
                    MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), requestBody);

                    Observable observable = DataRepository.getRetrofitInstance().create(AccountService.class)
                            .uploadFile(filePart);
                    BaseHttpObserver observer = new BaseHttpObserver<ResponseStatus<Object>>
                            (new HttpOnNextListener<ResponseStatus<Object>>() {
                                @Override
                                public void onSuccess(ResponseStatus<Object> dataResult) {

                                    if (dataResult.getResponseCode() == 0) {
                                        arrayList.add(dataResult.getData().toString());
                                        fileDto.setHttpPath(dataResult.getData().toString());
                                        if (photos.size() == arrayList.size()) {
                                            getController().dismissLoading();
                                        }
                                    }
                                }

                                @Override
                                public void onFail(String e) {


                                }

                                @Override
                                public void onComplete() {
                                }
                            });
                    DataRepository.getInstance().subscribe(observable, observer);

                }
            }

        }

    }


    public static class BusinessSettleStateHolder extends StateHolder {
        public final State<String> tenantName = new State<>("");
        public final State<String> contactName = new State<>("");
        public final State<String> contactMobile = new State<>("");
        public final State<String> bankReservedMobile = new State<>("");
        public final State<String> email = new State<>("");
        public final State<String> spid = new State<>("");
        public final State<String> companyAddress = new State<>("");
        public final State<String> typeId = new State<>("");
        public final State<String> typeName = new State<>("");
        public final State<String> zhhtMerchantsType = new State<>("");
        public final State<String> serviceCenterId = new State<>("");
        public final State<String> serviceCenterName = new State<>("");
        public final State<Boolean> checked = new State<>(false);

        public final State<List<LibraryInfo>> shopTypes = new State<>(new ArrayList<>());
        public final State<List<BusinessBean>> serviceTypes = new State<>(new ArrayList<>());
    }

    private JsonObject getHttpParams() {
        JsonObject params = new JsonObject();

        JsonArray identityPicUrls = new JsonArray();
        JsonArray companyPicUrls = new JsonArray();
        JsonArray licensePicUrls = new JsonArray();
        params.addProperty("tenantName", mStates.tenantName.get());
        params.addProperty("contactName", mStates.contactName.get());
        params.addProperty("contactMobile", mStates.contactMobile.get());
        params.addProperty("bankReservedMobile", mStates.bankReservedMobile.get());
        params.addProperty("email", mStates.email.get());
        params.addProperty("spid", mStates.spid.get());
        for (WorkOrderDetailBean.FileDto fileDto : mBinding.mprvCertificate.getPhotoPaths()) {
            identityPicUrls.add(fileDto.getHttpPath());
        }
        params.add("identityPicUrls", identityPicUrls);

        for (WorkOrderDetailBean.FileDto fileDto : mBinding.mprvCompany.getPhotoPaths()) {
            companyPicUrls.add(fileDto.getHttpPath());
        }
        params.add("companyPicUrls", companyPicUrls);
        for (WorkOrderDetailBean.FileDto fileDto : mBinding.mprvPermit.getPhotoPaths()) {
            licensePicUrls.add(fileDto.getHttpPath());
        }
        params.add("licensePicUrls", licensePicUrls);
        params.addProperty("companyAddress", mStates.companyAddress.get());
        params.addProperty("typeId", mStates.typeId.get());
        params.addProperty("zhhtMerchantsType", mStates.zhhtMerchantsType.get());
        params.addProperty("serviceCenterId", mStates.serviceCenterId.get());
        params.addProperty("checked", mStates.checked.get());

        return params;
    }

    public class ClickProxy {

        public void openRecord() {
            startActivity(new Intent().setClass(BusinessSettledActivity.this, BusinessSettleRecordActivity.class));
        }
        public void openWebview() {
            startActivity(new Intent()
                    .putExtra("id","1")
                    .putExtra("title","品质与服务承诺书")
                    .setClass(BusinessSettledActivity.this, WebViewApiActivity.class));
        }

        public void submit() {
            getController().displayLoading();
            mAccountRequester.addTenant(getHttpParams());
        }

        public void deliveryType() {

            OptionsPickerView<LibraryInfo> mOptionsPickerView = new OptionsPickerView.Builder(BusinessSettledActivity.this
                    , new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {

                    mStates.typeName.set(mStates.shopTypes.get().get(options1).getPickerViewText());
                    mStates.typeId.set(mStates.shopTypes.get().get(options1).getTypeId());
                }
            }).setTitleText("请选择分类").build();
            mOptionsPickerView.setPicker(mStates.shopTypes.get());
            mOptionsPickerView.show();
        }

        public void serviceType() {

            OptionsPickerView<BusinessBean> mOptionsPickerView = new OptionsPickerView.Builder(BusinessSettledActivity.this
                    , new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {

                    mStates.serviceCenterName.set(mStates.serviceTypes.get().get(options1).getPickerViewText());
                    mStates.serviceCenterId.set(mStates.serviceTypes.get().get(options1).getTypeId());
                }
            }).setTitleText("请选择分类").build();
            mOptionsPickerView.setPicker(mStates.serviceTypes.get());
            mOptionsPickerView.show();
        }
    }
}
